<?php

namespace App\Models\Shipping;

use App\Models\Currency;
use App\Models\Order\Extension;
use App\Models\Setting;
use App\Services\MobileApp\AppEnv;
use App\Services\Utils\FormatPrice;
use Illuminate\Database\Eloquent\Model;

class GeoZone extends Model
{
    const GEO_ZONE_NAME_WESTERN_REGION = 3; // '西部地区'
    const GEO_ZONE_NAME_WHOLE_COUNTRY = 4; // '全国'
    const GEO_ZONE_NAME_JZH = 5; // '江浙沪'

    const GEO_ZONE_ID_DEFAULT = 0; // 所有区域

    protected $table = 'geo_zone';
    protected $guarded = [];

    /**
     * @param $shipping_method_geo_zone_id
     * @param $code
     * @return array
     * @throws \Exception
     */
    public static function getGeoZoneShipping($shipping_method_geo_zone_id, $code)
    {
        $currency = AppEnv::currency();
        $cost = Setting::getShippingExtensionCost($shipping_method_geo_zone_id, $code);

        $shipping_quote = [
            'cost'         => $currency->exchangeOptionValuePrice($cost),
            'symbol_left'  => $currency->symbol_left,
            'symbol_right' => $currency->symbol_right,
        ];

        return $shipping_quote;
    }

    /**
     * @param $shipping_method_geo_zone_id
     * @param $code
     * @param null $currency
     * @return array
     * @throws \Exception
     */
    public static function getWeightShipping($shipping_method_geo_zone_id, $code, $currency = null)
    {
        $currency = $currency ?: Currency::fromEnv();

        $shipping_extension = (new Setting)
                ->where('key', Extension::SETTING_CODE_SHIPPING_PREFIX.$code.'_'.$shipping_method_geo_zone_id.Extension::SETTING_KEY_WEIGHT_RATE)
                ->first();

        $cost = $shipping_extension->value ?? 0;
        $shipping_cost = null;

        if ($cost) {
            $cost_split_by_weight = explode(',', $cost);

            foreach($cost_split_by_weight as $item)
            {
                list($weight, $cost_by_weight) = explode(':', $item);
                $shipping_cost[] = [
                    'weight' => $weight,
                    'cost'   => FormatPrice::formatPrice($cost_by_weight, $currency),
                ];
            }
        } else {
            $shipping_cost = 0;
        }

        $shipping_quote = [];

        $shipping_quote['cost'] = $shipping_cost;
        $shipping_quote['symbol_left'] = $currency->symbol_left;
        $shipping_quote['symbol_right'] = $currency->symbol_right;


        return $shipping_quote;
    }

}
